package com.matrix.job.handler;

import com.matrix.api.merchant.MerchantApi;
import com.matrix.api.order.OrderApi;
import com.matrix.api.product.ProductApi;
import com.xxl.job.core.handler.annotation.XxlJob;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.DubboReference;
import org.apache.dubbo.rpc.RpcException;
import org.springframework.stereotype.Component;

import java.util.Map;

/**
 * @author 有点甜
 * @since 2025/7/31
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class SalesStatsJobHandler {

    @DubboReference(check = false, timeout = 30000)
    private OrderApi orderApi;
    @DubboReference(check = false, timeout = 10000)
    private ProductApi productApi;
    @DubboReference(check = false, timeout = 10000)
    private MerchantApi merchantApi;

    @XxlJob("updateShopMonthlySalesJob")
    public void updateShopMonthlySalesJob() {
        log.info("XXL-JOB: 开始执行更新店铺月销量任务...");
        try {
            Map<Long, Integer> salesMap = orderApi.getMonthlySalesByShopIds(null);
            if (salesMap == null || salesMap.isEmpty()) {
                log.warn("XXL-JOB: 未找到需要更新的店铺销售数据");
                return;
            }
            log.info("XXL-JOB: 获取到 {} 个店铺的销售数据。", salesMap.size());
            merchantApi.batchUpdateMonthlySales(salesMap);
            log.info("XXL-JOB: 成功触发店铺月销量更新");

        } catch (Exception e) {
            log.error("XXL-JOB: 更新店铺月销量任务执行失败", e);
            throw new RuntimeException("更新店铺月销量任务失败", e);
        }
    }

    @XxlJob("updateProductMonthlySalesJob")
    public void updateProductMonthlySalesJob() {
        log.info("XXL-JOB: 开始执行更新菜品月销量任务...");
        try {
            Map<Long, Integer> salesMap = orderApi.getProductMonthlySales();
            if (salesMap == null || salesMap.isEmpty()) {
                log.warn("XXL-JOB: 未找到需要更新的菜品销售数据");
                return;
            }
            log.info("XXL-JOB: 获取到 {} 个菜品的销售数据。", salesMap.size());

            productApi.batchUpdateMonthlySales(salesMap);
            log.info("XXL-JOB: 成功更新菜品月销量");
        } catch (RpcException e) {
            log.error("XXL-JOB: 更新菜品月销量任务执行失败, RPC异常: {}", e.getMessage(), e);
            throw new RuntimeException("更新菜品月销量任务失败", e);
        } catch (Exception e) {
            log.error("XXL-JOB: 更新菜品月销量任务时发生未知异常", e);
            throw e;
        }
    }
}